package cn.gson.crm.controller.interview;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

import com.alibaba.fastjson.JSON;

import cn.gson.crm.controller.BaseServlet;
import cn.gson.crm.model.dao.AccessoryDao;
import cn.gson.crm.model.entity.Accessory;

/**
 * 文件上传,使用common-fileUpload处理上传文件
 */
@WebServlet("/upload")
public class UploadSerlvet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private AccessoryDao accessoryDao = new AccessoryDao();

	protected void post(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 判断是否是上传文件的请求类型
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		String upid = request.getParameter("upid");
		System.out.println("upid:"+upid);
		if (isMultipart) {
			try {
				Accessory accessory = new Accessory();
				// 通过这种方式，是获取不到表单的提交值
				// String userName = request.getParameter("userName");
				// System.out.println(userName);

				DiskFileItemFactory factory = new DiskFileItemFactory();
				// 设置单次请求文件的大小
				// factory.setSizeThreshold(1024 * 1024);
				// 创建一个上传文件处理器
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 设置每一个文件的最大大小
				// upload.setFileSizeMax(1024 * 1024);

				// 解析request
				List<FileItem> fileItems = upload.parseRequest(request);
				for (FileItem fileItem : fileItems) {
					// 获取表单的name值
					String fieldName = fileItem.getFieldName();
					// 表单的字段值
					InputStream stream = fileItem.getInputStream();
					if (fileItem.isFormField()) {
						// 表示当前这个item是一个普通表单字段
						String value = Streams.asString(stream);
						if(upid != "1"){
							accessory.setModel("order");
						}else{
							accessory.setModel(value);
						}
					} else {
						// 表示这个item是一个文件字段
						// 获取服务器的运行根目录
						String rootPath = request.getServletContext().getRealPath("/");

						// 创建文件上传的根目录
						File uploadDir = new File(rootPath, "upload");
						// 判断上传目录是否存在，不存在就创建
						if (!uploadDir.exists()) {
							uploadDir.mkdirs();
						}
						// 获取文件的原始名称xxxx.jpg
						String fileName = fileItem.getName();
						// 获取文件的后缀
						String suffix = fileName.substring(fileName.lastIndexOf("."));
						// 使用uuid生成新的文件名称
						String uuid = UUID.randomUUID().toString();
						File file = new File(uploadDir, uuid + suffix);

						// 将fileItem里面的inputStram写入file文件中。
						fileItem.write(file);
						
						accessory.setFileName(fileName);
						accessory.setFilePath("upload/" + uuid + suffix);
						accessory.setFileSize(file.length());
						if(upid != "1"){
							accessory.setUploadPerson(Long.parseLong(upid));
						}else{
							accessory.setUploadPerson(Long.parseLong("1"));
						}
					}
				}
				// 存储附件信息
				Long attId = accessoryDao.saveAccessory(accessory);
				if (attId != null) {
					accessory.setId(attId);
					response.getWriter().append(JSON.toJSONString(accessory));
				} else {
					response.getWriter().append("{\"message\":\"附件上传失败！\"}");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
